<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body{
      margin: 0;
      padding: 0;
      background: url(./grid.png);
    }
    #canvas{
      background-color: rgb(255, 192, 203, 0.4);
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="300px" height="300px"></canvas>
  <script>
    window.onload = function(){
      const canvas = document.getElementById('canvas')
      if(canvas.getContext){
        const ctx = canvas?.getContext('2d')

        const imgSun = new Image()
        imgSun.src = '../02-Canvas/images/canvas_sun.png'
        const imgEarth = new Image()
        imgEarth.src = '../02-Canvas/images/canvas_earth.png'
        const imgMoon = new Image()
        imgMoon.src = '../02-Canvas/images/canvas_moon.png'


        requestAnimationFrame(draw)

        function draw(){
          ctx.clearRect(0, 0, 300, 300)
          ctx.drawImage(imgSun, 0, 0)

          // 1. 绘制太阳、轨道
          ctx.save()
          ctx.translate(150, 150)
          ctx.beginPath()
          ctx.arc(0, 0, 100, 0, Math.PI * 2, false)
          // ctx.moveTo(0 , 0)
          // ctx.lineTo(150, 0)
          ctx.closePath()
          ctx.strokeStyle = 'gray'
          ctx.stroke()
          ctx.restore()

          const date = new Date()
          const seconds = date.getSeconds()
          const milliSeconds = date.getMilliseconds()

          // 2.绘制地球、月球
          ctx.save()
          ctx.translate(150, 150)
          ctx.rotate(Math.PI / 30 * seconds + Math.PI / 30000 * milliSeconds)
          ctx.translate(100, 0)
          ctx.drawImage(imgEarth, -12, -12)
          // 地球的阴面
          ctx.save()
          ctx.fillStyle = 'rgba(0, 0, 0, 0.4)'
          ctx.fillRect(0, -12, 12, 24)
          ctx.restore()
          // 相对地球绘制月球
          ctx.save()
          ctx.rotate(Math.PI / 10 * seconds + Math.PI / 10000 * milliSeconds)
          ctx.translate(25, 0)
          ctx.drawImage(imgMoon, -4, -4)
          ctx.restore()
          ctx.restore()

          requestAnimationFrame(draw)
        }
      }
    }
  </script>
</body>
</html>